package com.xxy.controller;

import com.xxy.context.BaseContext;
import com.xxy.entity.User;
import com.xxy.entity.dto.LoginDTO;
import com.xxy.entity.dto.UserQueryDTO;
import com.xxy.entity.vo.LoginVO;
import com.xxy.properties.JwtProperties;
import com.xxy.result.PageResult;
import com.xxy.result.Result;
import com.xxy.service.IUserService;
import com.xxy.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录
     *
     * @param
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO) {
        User user = userService.selectByUsername(loginDTO.getUsername());

        if (user == null) {
            return Result.error("登录失败,用户不存在");
        } else if (!user.getPassword().equals(loginDTO.getPassword())) {
            return Result.error("登录失败,密码错误");
        } else {
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getId());
            String token = JwtUtil.createJWT(
                    jwtProperties.getUserSecretKey(),
                    jwtProperties.getUserTtl(),
                    claims
            );
            String role = "user";
            if ("admin".equals(user.getUsername())) {
                role = "admin";
            }
            LoginVO loginVO = LoginVO.builder()
                    .id(user.getId())
                    .username(loginDTO.getUsername())
                    .password(loginDTO.getPassword())
                    .token(token)
                    .role(role)
                    .build();

            return Result.success(loginVO);
        }
    }

    /**
     * 用户注册
     *
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody LoginDTO loginDTO) {
        User user = userService.selectByUsername(loginDTO.getUsername());
        //如果用户不存在
        if (user == null) {
            User newUser = User.builder().username(loginDTO.getUsername()).password(loginDTO.getPassword()).build();
            userService.save(newUser);
            return Result.success("注册成功");
        } else {
            return Result.error("注册失败,该用户已存在");
        }
    }

    @PutMapping("/update")
    public Result updateUser(@RequestBody User user) {
        user.setId(BaseContext.getCurrentId());
        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);
        return Result.success("修改成功");
    }
    @DeleteMapping("/delete/{id}")
    public Result deleteUser(@PathVariable("id") Integer id) {
        userService.removeById(id);
        return Result.success("删除成功");
    }
    @GetMapping("/getUserById/{id}")
    public Result getUserById(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        return Result.success(user);
    }
    @GetMapping("/getUserInfo")
    public Result<User> getUserInfo() {
        Long id = BaseContext.getCurrentId();
        User user = userService.getById(id);
        return Result.success(user);
    }
    @PostMapping("/query")
    public Result<PageResult> query(@RequestBody UserQueryDTO userQueryDTO) {
        PageResult pageResult = userService.query(userQueryDTO);
        return Result.success(pageResult);
    }
}
